package com.bwie.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bwie.utils.R;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.Dict;
import com.bwie.mapper.DictMapper;
import com.bwie.service.DictService;

import javax.annotation.PostConstruct;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService{
    @Autowired
    DictMapper dictMapper;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @PostConstruct
    public void getdictList(){
        List<Dict> dictList = dictMapper.selectList(null);
        for (Dict dict : dictList) {
            String key1 = "dict:" + dict.getDictType();
            String key2 = "" + dict.getDictName();
            stringRedisTemplate.opsForHash().put(key1, key2, JSON.toJSONString(dict));
        }
        System.out.println("字典表加载完成");
    }

    @Override
    public R dictList(Integer typeId) {
        String key1="dict:"+typeId;
        Boolean b = stringRedisTemplate.hasKey(key1);
        if(b){
            System.out.println("从缓存中");
            List<Object> objectList = stringRedisTemplate.opsForHash().values(key1);
            ArrayList<Dict> list = new ArrayList<>();
            for (Object object : objectList) {
                Dict dict = JSON.parseObject(object.toString(), Dict.class);
                list.add(dict);
            }
            return R.OK(list);
        }
        //缓存不存在从数据库
        List<Dict> dictList = dictMapper.selectList(new QueryWrapper<Dict>().lambda().eq(Dict::getDictType, typeId));
        for (Dict dict : dictList) {
            key1="dict:"+dict.getDictType();
            String key2=""+dict.getDictName();
            stringRedisTemplate.opsForHash().put(key1, key2, JSON.toJSONString(dict));
        }
        return R.OK(dictList);
    }
}
